import QtQuick 2.8
import QtQuick.Layouts 1.3
import QtGraphicalEffects 1.0
import "components"

GridLayout {
    id: grid
    property bool newUser: false // Switch signal userlist < > usernameBox view.
    readonly property string usernameValue: newUser ? usernameBox.text : userlist.selectedUserLogin
    readonly property string passwordValue: passwordBox.text

    // For Skel.qml & javascript function.
    readonly property real miniloginSize: Math.round(miniloginButton.width + miniloginButton.anchors.leftMargin)

    implicitWidth: isFull ? root.width : taskbarSize
    LayoutMirroring.enabled: isMirror
    anchors.left: parent.left
    columns: (isHalf || isFull) ? 1 : 999
    columnSpacing: 0 // = Vertical (view) adjust.
    rowSpacing: 45

    // From userlist to Skel.qml : Propagation "onClicked" like.
    signal userSelected()  
    signal userDeselected()
    // ==============
    // Row/Column 1/2
    // ==============

    Item {
        Layout.preferredWidth: isFull ? root.width : isHalf ? taskbarSize : iconSize
        Layout.preferredHeight: columnUserLogin.visible ? 0 : (grid.newUser ? newUserAvatar.height : userlist.height)

        UserList {
            id: userlist
            //width: isFull ? root.width : implicitWidth
            anchors.horizontalCenter : parent.horizontalCenter
            width: 476
            //orientationUserlist: (isHalf || isFull) ? "horizontal" : "vertical"
            showUsername: (isHalf || isFull) ? true : false
            //clip: (isFull || !isHalf) ? false : true
            visible: grid.newUser ? false : true
            opacity: visible ? 1 : 0
            Behavior on opacity { NumberAnimation { duration: 250 } }
            onUserSelected: {
                grid.newUser = false;
                visible = false;
                columnUserLogin.visible = true;
                grid.userSelected();
            }
        }

        ActionButton {
            anchors.top: userlist.bottom
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.topMargin: -10
            visible: userlist.visible
            width: userList.width
            enabled: true
            height: 24

            Text {
                id: txtNewUser
                anchors.centerIn: parent
                font.pixelSize: 18
                font.family: 'PT Root UI'
                text: 'Нет в списке?'
            }

            onClicked: {
                grid.newUser = true;
                userlist.visible = false;
                columnUserLogin.visible = true;
                grid.userSelected();
            }
        }
    }

    // ==============
    // Row/Column 2/2
    // ==============

    ColumnLayout {
        id: columnUserLogin
        Layout.preferredWidth: isFull ? root.width : taskbarSize
        LayoutMirroring.enabled: isMirror
        spacing: 0

        visible: false

        Item {
            Layout.alignment: Qt.AlignHCenter
            Layout.fillWidth: false
            Layout.fillHeight: false
            Layout.preferredWidth: 112
            Layout.preferredHeight: 88
            Layout.bottomMargin: 20
            Rectangle {
                id: roundMask
                width: 112
                height: 88
                radius: 44
                color: '#FFF'
                visible: false
            }
            Image {
                id: avatar
                anchors.fill: parent
                source: userlist.selectedUserAvatarPath
                fillMode: Image.PreserveAspectCrop
                Component.onCompleted: {
                    status != Image.Error && status != Image.Null 
                        || (source = './components/artwork/face.svg');
                }
                layer.enabled: true
                layer.effect: OpacityMask {
                    source: avatar
                    maskSource: roundMask
                }
            }
        }

        UsernameLabel {
            id: userNameLabel
            Layout.leftMargin: 4
            Layout.rightMargin: 4
            Layout.alignment: Qt.AlignHCenter
            Layout.bottomMargin: 42
            text: userlist.selectedUserName
            visible: !grid.newUser
            opacity: visible ? 1 : 0
            Behavior on opacity { NumberAnimation { duration: 250 } }
        }

        TextBox {
            id: usernameBox
            Layout.alignment: (isHalf || isFull) ? Qt.AlignCenter : Qt.AlignVCenter | Qt.AlignLeft
            Layout.bottomMargin: 24
            Layout.preferredWidth: textboxWidth()
            Layout.topMargin: 5
            echoMode: TextInput.Normal
            placeholderText: textConstants.userName
            clearButtonShown: true
            revealPasswordButtonShown: false
            focus: visible ? true : false
            visible: textboxVisible() && grid.newUser
            opacity: visible ? 1 : 0
            Behavior on opacity { NumberAnimation { duration: 250 } }
            onAccepted: passwordBox.forceActiveFocus()
            // See : https://github.com/sddm/sddm/issues/202 (keyboard.layouts)
        }

        Item {
            Layout.fillWidth: true
            Layout.preferredHeight: columnLogin.implicitHeight

            Rectangle {
                anchors {
                    right: columnLogin.left
                    verticalCenter: columnLogin.verticalCenter
                    rightMargin: 12
                }
                width: 58
                height: 58
                radius: width / 2
                color: '#73FFFFFF'
                Image {
                    anchors.centerIn: parent
                    width: 22
                    height: 22
                    source: 'components/artwork/buttons/back.svg'
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        grid.newUser = false;
                        userlist.visible = true;
                        grid.userDeselected();
                        columnUserLogin.visible = false;
                    }
                }
            }

            ColumnLayout {
                id: columnLogin
                anchors.top: parent.top
                anchors.topMargin: -10
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 4
                TextBox {
                    id: passwordBox
                    Layout.alignment: (isHalf || isFull) ? Qt.AlignCenter : Qt.AlignVCenter | Qt.AlignLeft
                    Layout.preferredWidth: textboxWidth()
                    Layout.topMargin: 5
                    echoMode: TextInput.Password
                    placeholderText: textConstants.password
                    clearButtonShown: true
                    revealPasswordButtonShown: true
                    focus: usernameBox.visible ? false : true
                    visible: textboxVisible()
                        opacity: visible ? 1 : 0
                        Behavior on opacity { NumberAnimation { duration: 250 } }
                    onAccepted: {
                        grid.login();
                    }

                    onVisibleChanged: {
                        if (visible) forceActiveFocus();
                    }
                }

                NotificationMessage {
                    id: notification
                    LayoutMirroring.enabled: isMirror
                    Layout.maximumWidth: isFull ? root.width : isHalf ? taskbarSize : (taskbarSize - iconSize)
                    Layout.minimumWidth: (taskbarSize - iconSize)
                    Layout.fillWidth: true
                    Layout.preferredHeight: text == "" ? 1 : implicitHeight
                    Layout.leftMargin: 20
                    Layout.rightMargin: 4
                    horizontalAlignment: Text.AlignLeft
                    visible: textboxVisible()
                }
            }
        }
    }

    //Item { id: keepmeImAutoWidthAnchor; anchors.fill: parent } //finalydontkeepmeidoshit

    function textboxWidth() { 
        if (!isFull) {
            var size = (taskbarSize - iconSize) - miniloginSize;
            if (size < 0) return 0;
            if (size > parseInt(config["textfield/width"])) return parseInt(config["textfield/width"]);
            return size;
        }
        return parseInt(config["textfield/width"]);
    }

    function textboxVisible() { 
        if (!isFull) {
            var size = (taskbarSize - iconSize) - miniloginSize;  
            if (size < parseInt(config["textfield/width.min"])) return false;
        }
        return true;
    }


    // ==============
    // Misc
    // ==============

    Keys.onPressed: {
        if (event.key == Qt.Key_Left)  userlist.decrementCurrentIndex();
        if (event.key == Qt.Key_Right) userlist.incrementCurrentIndex();
        if (event.key == Qt.Key_Up)    userlist.incrementCurrentIndex();
        if (event.key == Qt.Key_Down)  userlist.decrementCurrentIndex();
    }

    Connections {
        target: sddm
        onLoginSucceeded: grid.opacity = 0
        onLoginFailed: { 
            notification.msg = textConstants.loginFailed;
            passwordBox.selectAll();
            passwordBox.forceActiveFocus();
        }
    }

    function login() {
        if (grid.usernameValue !== "") {
            sddm.login(grid.usernameValue, grid.passwordValue, sessionButton.currentIndex);
        }
    }

}
